<template>
  <div v-loading="loading" class="loading_container" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addData">添加类型</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div class="search">
        <el-input clearable v-model="name" placeholder="关键词搜索" @keyup.enter="getList" />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table_list">
      <el-table border stripe resizable @selection-change="handleChange" :data="tableData" ref="tableDom" height="100%"
        style="position:absolute">
        <el-table-column show-overflow-tooltip type="selection" width="40" />

        <!-- 序号 -->
        <el-table-column show-overflow-tooltip type="index" :index="indexMethod" label="序号" width="50" />

        <!-- 类型名称 -->
        <el-table-column show-overflow-tooltip prop="name" label="类型名称" min-width="200" />

        <!-- 状态 -->
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="!scope.row.status">启用</HStatus>
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />

        <!-- 更新时间 -->
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="editData(scope.row)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <Pagination ref="pagination" :list_total="total" @size-change="getList" @current-change="getList" />
    </div>

    <!-- 添加/编辑  类型弹窗 -->
    <HModal v-model="addDialog" size="small">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ dialogTitle }}</h3>
        </div>
      </template>
      <div v-loading="dialogLoading">
        <el-form label-width="70" ref="formRef" :rules="rules" :model="form" class="form_content"
          @validate="handleFormValidate">
          <!-- 类型名称 -->
          <el-form-item label="类型名称" :class="{
    form_item: formValidateResult['name'],
    validate_fail: !formValidateResult['name'],
  }" prop="name">
            <el-input v-model="form.name" clearable placeholder="请输入名称" />
          </el-form-item>

          <!-- 类型状态 -->
          <el-form-item label="类型状态" class="last_form_item">
            <el-radio-group v-model="form.status" class="el-group">
              <el-radio :value="false">
                <span class="bg_text">启用</span>
              </el-radio>
              <el-radio :value="true">
                <span class="bg_text">禁用</span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <template #footerLeft>
        <HPlainBgButton is-modal type="error" @click="changeStatus(4)" v-show="dialogTitle === '编辑分类'">删除
        </HPlainBgButton>
      </template>

      <template #footerRight>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="onClose"> 取消 </HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ref, reactive, markRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormItemProp } from 'element-plus'
import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
import { typeList, typeSave, typeDisable, typeDelete } from '@/api/goodsSet'
import HPlainButton from '@/components/common/button/HPlainButton.vue'
import HButton from '@/components/common/button/HButton.vue'
import HStatus from '@/components/common/status/HStatus.vue'
import HLink from '@/components/common/link/HLink.vue'
import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
import HModal from '@/components/common/Modal/HModal.vue'

//列表序号
const indexMethod = (index: number) => {
  return (index + 1) * 1
}
const loading = ref(false)
const name = ref('') // 名称
const tableData = ref([]) // 列表数据
const tableDom = ref() // 列表dom
const pagination = ref() // 分页dom
const total = ref(0) // 总数目
const addDialog = ref(false)
const dialogTitle = ref('')
const dialogLoading = ref(false)

const formRef = ref<FormInstance>() // 表单元素
// 表单数据
const form = reactive({
  id: null,
  name: '',
  status: false,
})

// 验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入类型名称', trigger: ['blur', 'change'] }],
})

/**
 * 表单验证结果
 */
const formValidateResult = ref({
  name: true,
})

/**
 * 表单验证方法
 */
const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
  formValidateResult.value.name = isValid
}

/**
 * 弹窗关闭方法
 */
const onClose = () => {
  addDialog.value = false
  formValidateResult.value.name = true
}

// 获取列表选中的数据
const selecttion = ref([])
const handleChange = (val) => {
  if (val.length != 0) {
    val.forEach((item) => {
      if (selecttion.value.indexOf(item.id) == -1) {
        selecttion.value.push(item.id)
      } else {
        selecttion.value = selecttion.value.filter((i) => i == item.id)
      }
    })
  } else {
    selecttion.value = []
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  const data = {
    name: name.value,
    limit: pagination.value.size,
    page: pagination.value.current,
  }
  await typeList(data).then((res) => {
    tableData.value = res.data.data.rows
    total.value = parseInt(res.data.data.total)
  })
  loading.value = false
}

// 添加类型
const addData = () => {
  dialogTitle.value = '添加分类'
  addDialog.value = true
  form.id = null
  form.name = ''
  form.status = false
}

// 编辑类型
const editData = (obj) => {
  dialogTitle.value = '编辑分类'
  addDialog.value = true
  form.id = obj.id
  form.name = obj.name
  form.status = obj.status
}

// 保存方法
const saveDataMethod = (method, data) => {
  dialogLoading.value = true
  method(data).then((res) => {
    dialogLoading.value = false
    if (res.data.isError)
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'warning',
        duration: 2000,
      })
    if (res.data.success == true) {
      addDialog.value = false
      getList()
      formValidateResult.value.name = true
    }
  })
}

// 保存数据
const saveData = (formEl: FormInstance | undefined) => {
  formEl.validate((valid) => {
    if (valid) {
      saveDataMethod(typeSave, form)
    }
  })
}

// 修改状态方法
const changeMethod = (type, method, arr, status, dialog) => {
  if (arr.length == 0) {
    ElMessage({
      message: `请选择要${type}的类型`,
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    type: type == '删除' ? 'error' : 'warning',
    title: '提示',
    icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
    message: `确认${type}选中的类型?`,
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    autofocus: false,
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 1000)
      } else {
        done()
      }
    },
  }).then(async () => {
    if (status != 3) {
      await method(arr, status).then((res) => {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'warning',
            duration: 2000,
          })
        if (res.data.success) {
          selecttion.value = []
          tableDom.value.clearSelection()
          getList()
        }
      })
    } else {
      await method(arr).then((res) => {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'warning',
            duration: 2000,
          })
        if (res.data.success) {
          selecttion.value = []
          tableDom.value.clearSelection()
          getList()
          if (dialog != '') {
            addDialog.value = false
          }
        }
      })
    }
  })
}

// 批量启用/禁用/删除
const changeStatus = (n) => {
  if (n == 1) {
    changeMethod('启用', typeDisable, selecttion.value, false, '')
  }
  if (n == 2) {
    changeMethod('禁用', typeDisable, selecttion.value, true, '')
  }
  if (n == 3) {
    changeMethod('删除', typeDelete, selecttion.value, 3, '')
  }
  if (n == 4) {
    changeMethod('删除', typeDelete, [form.id], 3, addDialog)
  }
}

defineExpose({ getList })
</script>

<style scoped lang="scss">
   .loading_container {
    display: flex;
    flex-direction: column;
    flex: 1;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 12px 0 ;

      .btn_group {
        display: flex;
        gap: 5px;
      }

      .search {
        display: flex;
        gap: 5px;
      }
    }

    .table_list {
      position: relative;
             flex: 1;
             margin: 0 0 12px ;
    }

    .footer {
      height: 28px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .form_content {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
</style>
